package com.yunshu.yunshuapp;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yunshu.yunshuapp.banner.ScrollBanner;
import com.yunshu.yunshuapp.kuaixun.KuaixunListActivity;
import com.yunshu.yunshuapp.tongxunlu.TongxunluActivity;
import com.yunshu.yunshuapp.user.LoginActivity;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;
import com.yunshu.yunshuapp.xianhuo.Xianhuo;
import com.yunshu.yunshuapp.xianhuo.XianhuoActivity;
import com.yunshu.yunshuapp.xianhuo.XianhuoClickListener;
import com.yunshu.yunshuapp.xianhuo.XianhuoDetailActivity;
import com.yunshu.yunshuapp.xianhuo.XianhuoDetailActivity2;
import com.yunshu.yunshuapp.zixunlist.ZixunListActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhouwenjie on 2017/1/27.
 */
public class HomeListAdapter extends RecyclerView.Adapter implements OnTapListener {

    public static final int HOME_ITEM_TYPE_BANNER = 1;
    public static final int HOME_ITEM_TYPE_BUTTON = 2;
    public static final int HOME_ITEM_TYPE_LISTCELL = 3;
    private final ImageLoader mImageLoader;
    private final DisplayImageOptions options;
    private ArrayList<Xianhuo> models;
    public OnTapListener tapListener;
    public AppCompatActivity activity;
    public XianhuoClickListener onClickListener;
    public String[] ads;
    public BannerHolder bannerHolder;
    public Boolean shouldShowAudit = false;

    public HomeListAdapter(Context context){
        // 使用ImageLoader之前初始化
        YSUtils.initImageLoader(context);

        models = new ArrayList<>();
        // 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();
        options = YSUtils.displayImageOptions();

        tapListener = this;
    }

    @Override
    public int getItemCount() {

        int count = models.size() + 2;
        return count ;
    }

    @Override
    public int getItemViewType(int position) {
        int listType = -1;
        if (position == 0 ){

            listType = HOME_ITEM_TYPE_BANNER;

        }else if(position == 1){

            listType = HOME_ITEM_TYPE_BUTTON;

        }else {

            listType = HOME_ITEM_TYPE_LISTCELL;

        }
        return listType;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == HOME_ITEM_TYPE_BANNER){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.banner_container,parent,false);
            bannerHolder = new BannerHolder(view);
            return bannerHolder;
        }else if(viewType == HOME_ITEM_TYPE_BUTTON){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_buttons_container,parent,false);
            ButttonsHolder holder = new ButttonsHolder(view);
            return holder;
        }else{
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.xianhuo_list_item2,parent,false);
            ListViewHolder holder = new ListViewHolder(view);
            holder.tapListener = this;
            return holder;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (position >= models.size() + 2) return;
        if (position == 0){
            bannerHolder.updateBanner();
            return;

        }else if(position == 1){

            return;

        }else {
            Xianhuo model = models.get(position - 2 );
            ListViewHolder xhHolder = (ListViewHolder) holder;
            xhHolder.setPosition(position);
            xhHolder.categoryTV.setText(model.getChannelname());
            mImageLoader.displayImage(model.getKucunpic(), xhHolder.imgView);
            xhHolder.dateTV.setText(model.getCreatetime());
            xhHolder.locationTV.setText(model.getPlace());

            if (model.getProductname().length()>0) {
                xhHolder.categoryTV.setText(model.getChannelname() + "(" + model.getProductname() + ")");
            }else {
                xhHolder.categoryTV.setText(model.getChannelname() );
            }
            xhHolder.dateTV.setText(model.getCreatetime());
            xhHolder.titleTV.setText(model.getAdvert());
            xhHolder.companyTV.setText("公司: "+model.getCompany());
            return;
        }

    }

    private SpannableStringBuilder createPriceStyle(String price){

        int startIndex=-1 , endIndex = price.length() - 1;

        for (int i = 0 ; i < price.length() ; i++ ){
            Character c = price.charAt(i);
            if (c >= '0' && c <= '9'){
                if (startIndex < 0 ){
                    startIndex = i;
                }
            }else {
                if (startIndex >= 0 ){
                    endIndex = i;
                    break;
                }
            }
        }

        SpannableStringBuilder style=new SpannableStringBuilder(price);
        if (startIndex > 0) {
            style.setSpan(new ForegroundColorSpan(YSUtils.getColor(R.color.title_gray2,this.activity)),0,startIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //设置指定位置文字的颜色
            style.setSpan(new RelativeSizeSpan(0.8f),0,startIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //设置指定位置文字的颜色
        }

        if (endIndex < price.length() - 1){
            style.setSpan(new ForegroundColorSpan(YSUtils.getColor(R.color.title_gray2,this.activity)),endIndex,price.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //设置指定位置文字的颜色
            style.setSpan(new RelativeSizeSpan(0.8f),endIndex,price.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //设置指定位置文字的颜色

        }

        return style;
    }

    @Override
    public void onSingleTap(View v, int position) {
        Xianhuo model = models.get(position-2);

        if (this.onClickListener != null){
            this.onClickListener.onClick(model);
            return;
        }

        if ("image".equals( v.getTag()) ){
            Intent intent = new Intent();
            intent.setClass(activity, ImageActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("imgUrl",model.getKucunpic());
            intent.putExtras(bundle);
            activity.startActivityForResult(intent,0);
            return;
        }

        Intent intent = new Intent();
        intent.setClass(this.activity, XianhuoDetailActivity2.class);
        Bundle bundle = new Bundle();

        String url = "http://www.yunshutech.com/order.action#offer?fromApp=1&id=" + model.getXianhuoId();
        bundle.putString("url",url);
        bundle.putString("title","现货详情");
        bundle.putString("xianhuo",model.serializeToString());
        intent.putExtras(bundle);
        this.activity.startActivityForResult(intent,0);
    }

    public static class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView categoryTV;
        public ImageView imgView;
        public TextView dateTV;
        public TextView locationTV;

        public TextView companyTV;
        public TextView titleTV;
        public int mPosition;
        public OnTapListener tapListener;
        private ImageView locationImg;

        public ListViewHolder(View itemView ) {
            super(itemView);
            itemView.setOnClickListener(this);

            imgView = (ImageView) itemView.findViewById(R.id.imageView);
            imgView.setTag("image");
            imgView.setOnClickListener(this);

            categoryTV = (TextView) itemView.findViewById(R.id.typeTV);
            dateTV = (TextView) itemView.findViewById(R.id.dateTV);
            locationTV = (TextView) itemView.findViewById(R.id.locationTV);
            companyTV = (TextView) itemView.findViewById(R.id.companyTV);
            titleTV = (TextView) itemView.findViewById(R.id.titleTV);
            locationImg = (ImageView)itemView.findViewById(R.id.locImg);

        }

        public void setPosition(int position) {
            mPosition = position;
        }

        @Override
        public void onClick(View view) {
            tapListener.onSingleTap(view,mPosition);
        }

        public void setAuditDes(String audit) {
            if ("0".equalsIgnoreCase(audit)){
                locationTV.setText("待审核");
            }else if ("1".equalsIgnoreCase(audit)){
                locationTV.setText("审核通过");
            }else if ("2".equalsIgnoreCase(audit)){
                locationTV.setText("审核不通过");
            }
            locationTV.setTextColor(Color.RED);
            locationImg.setVisibility(View.INVISIBLE);

        }

    }

    class ButttonsHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public ButttonsHolder(View itemView ) {
            super(itemView);

//            ViewGroup.LayoutParams layout = itemView.getLayoutParams();
//            layout.height = 290;
//            itemView.setLayoutParams(layout);

            Button kuaixunBtn = (Button) itemView.findViewById(R.id.kuaixun);
            kuaixunBtn.setOnClickListener(this);

            Button zixunBtn = (Button) itemView.findViewById(R.id.zixun);
            zixunBtn.setOnClickListener(this);

            Button xianhuoBtn = (Button) itemView.findViewById(R.id.xianhuo);
            xianhuoBtn.setOnClickListener(this);

            Button tongxunluBtn = (Button) itemView.findViewById(R.id.tongxunlu);
            tongxunluBtn.setOnClickListener(this);

        }

        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.tongxunlu){
                if ( YSUser.instance().getContacts() == 1){
                    Intent intent = new Intent();
                    intent.setClass(activity,TongxunluActivity.class);
                    activity.startActivityForResult(intent,0);
                }else{
                    alertNoTongxunlu();
                }

            }else if(view.getId() == R.id.kuaixun){
                Intent intent = new Intent();
                if (YSUser.isLogin()) {
                    intent.setClass(activity,KuaixunListActivity.class);
                }else{
                    intent.setClass(activity, LoginActivity.class);
                }
                activity.startActivityForResult(intent,0);
            }else if(view.getId() == R.id.zixun){
                Intent intent = new Intent();
                intent.setClass(activity,ZixunListActivity.class);
                activity.startActivityForResult(intent,0);
            }else if(view.getId() == R.id.xianhuo){
                Intent intent = new Intent();
                if (YSUser.isLogin()) {
                    intent.setClass(activity,XianhuoActivity.class);
                }else{
                    intent.setClass(activity, LoginActivity.class);
                }
                activity.startActivityForResult(intent,0);
            }
        }

        private void alertNoTongxunlu() {
            new AlertDialog.Builder(activity).setTitle("提示")//设置对话框标题

                    .setMessage("您暂时没有开通该功能，是否立刻联系客服开通此功能？")//设置显示的内容 ;
                    .setPositiveButton("拨打电话",new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                            Intent phone = new Intent();
                            phone.setData(Uri.parse("tel:" + activity.getString( R.string.TEL_400)));
                            phone.setAction(Intent.ACTION_DIAL);
                            //开启系统拨号器
                            activity.startActivity(phone);
                        }
                    })
                    .setNegativeButton("返回",new DialogInterface.OnClickListener() {//添加返回按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//响应事件
                            Log.i("alertdialog"," 请保存数据！");
                        }
                    }).show();//在按键响应事件中显示此对话框
        }
    }

    class BannerHolder extends RecyclerView.ViewHolder {

        public ScrollBanner banner;

        public BannerHolder(View itemView ) {
            super(itemView);

            int screenWidth = YSUtils.screenWidth(activity); // 获取屏幕宽度
            banner = (ScrollBanner)itemView.findViewById(R.id.homepageBanner);
            ViewGroup.LayoutParams layout = itemView.getLayoutParams();
            layout.width = screenWidth;
            layout.height = (int) (screenWidth*0.432) + 1;
            itemView.setLayoutParams(layout);

            banner.bannerClickListener = new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    int index = banner.indexOfView(v);
                    Intent intent = new Intent();
                    intent.setClass(activity, ImageActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("imgUrl",ads[index]);
                    intent.putExtras(bundle);
                    activity.startActivityForResult(intent,0);
//                MainActivity.this.finish();
                }
            };
        }

        public void updateBanner(){
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ads!= null && ads.length > 0 && banner.adList == null)
                        banner.setImages( ads );
                }
            });
        }
    }

    public void setModels(List<Xianhuo> newModels){
        models.clear();
        models.addAll(newModels);
    }

    public void addFooterItem(List<Xianhuo> footerDatas) {
        models.addAll(footerDatas);
        notifyDataSetChanged();
    }
}
